import json
import os

CONFIG_DIR = 'configs'


class ConfigManager:
    def __init__(self):
        self.ensure_config_dir()
        self.configs = self.load_all_configs()

    @staticmethod
    def ensure_config_dir():
        if not os.path.exists(CONFIG_DIR):
            os.makedirs(CONFIG_DIR)
        # 确保有默认配置
        default_path = os.path.join(CONFIG_DIR, 'default.json')
        if not os.path.exists(default_path):
            with open(default_path, 'w', encoding='utf-8') as f:
                json.dump({
                    "title_color": "#36648B",
                    "font_name": "仿宋",
                    "font_size": 12,
                    "bold": False,
                    "title_height": 25,
                    "row_height": 20,
                    "col_widths": {
                        "A": 15,
                        "B": 20,
                        "C": 20,
                        "D": 20,
                        "E": 100,
                        "F": 10,
                        "G": 20,
                        "H": 10,
                        "I": 20
                    }
                }, f, indent=2)

    @staticmethod
    def load_all_configs():
        """加载所有配置文件"""
        configs = {}
        for fname in os.listdir(CONFIG_DIR):
            if fname.endswith('.json'):
                name = fname.replace('.json', '')
                with open(os.path.join(CONFIG_DIR, fname), 'r', encoding='utf-8') as f:
                    configs[name] = json.load(f)
        return configs

    def get_config(self, name='default'):
        return self.configs.get(name, self.configs['default'])

    def save_config(self, name, config):
        path = os.path.join(CONFIG_DIR, f"{name}.json")
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2)
        self.configs[name] = config
